package com.pansoft.openplanet.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.SwitchCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.widget.RoundImageView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.recycleviewhelper.CommonAdapter;
import com.efounder.recycleviewhelper.base.ViewHolder;
import com.efounder.util.AppContext;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.google.gson.Gson;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.TotalAssetAddBean;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 总资产添加界面
 *
 * @author YQS 2018/08/20
 */
public class TotalAssetsAddActivity extends BaseActivity implements View.OnClickListener {

    public static final String TAG = "TotalAssetsAddActivity";

    private SmartRefreshLayout refreshLayout;
    private ImageView ivBack;
    private TextView tvTitle;
    private TextView tvSave;
    private RecyclerView recyclerView;
    private TotalAssetAddAdapter addAdapter;
    private List<TotalAssetAddBean.AllTrusteeshipCoinBean> assetsBeanList;

    public static void start(Context context) {
        Intent starter = new Intent(context, TotalAssetsAddActivity.class);
//    starter.putExtra();
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_total_assets_add);
        initView();
        initData();
    }


    private void initView() {
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvSave = (TextView) findViewById(R.id.tv_save);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                requestData();
            }
        });

    }


    private void initData() {
        tvTitle.setText("添加资产");
        assetsBeanList = new ArrayList<>();
        addAdapter = new TotalAssetAddAdapter(this, R.layout.open_planet_item_total_asset_add, assetsBeanList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(addAdapter);
        refreshLayout.autoRefresh();
    }

    private void requestData() {

        HashMap<String, String> params = new HashMap<>();
        params.put("userId", EnvironmentVariable.getUserName());
        TCRequestUtil.getCommonRequest(TAG, "trusteeship/allTrusteeshipCoin", params, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                refreshLayout.finishRefresh(100);
                assetsBeanList.clear();
                addAdapter.notifyDataSetChanged();
                try {
                    TotalAssetAddBean bean = new Gson().fromJson(response, TotalAssetAddBean.class);
                    assetsBeanList.addAll(bean.getAllTrusteeshipCoin());
                    addAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), "数据异常");
                }
            }

            @Override
            public void onFail(String error) {
                refreshLayout.finishRefresh(100);
                ToastUtil.showToast(AppContext.getInstance(), "获取数据失败");

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void back(View view) {
        setResult(RESULT_OK);
        super.back(view);
    }

    public class TotalAssetAddAdapter extends CommonAdapter<TotalAssetAddBean.AllTrusteeshipCoinBean> {
        private Context context;

        public TotalAssetAddAdapter(Context context, int layoutId, List datas) {
            super(context, layoutId, datas);
            this.context = context;
        }

        @Override
        protected void convert(ViewHolder holder, final TotalAssetAddBean.AllTrusteeshipCoinBean o, int position) {
            RoundImageView ivIcon;
            TextView ivAssetName;
            SwitchCompat switchButton;
            LinearLayout itemLayout;

            ivIcon = holder.getView(R.id.iv_icon);
            ivAssetName = holder.getView(R.id.iv_asset_name);
            switchButton = holder.getView(R.id.switch_button);
            itemLayout = holder.getView(R.id.item_layout);
            LXGlideImageLoader.getInstance().displayImage(context, ivIcon, o.getCoinIcon());
            ivAssetName.setText(o.getCoinName());
            switchButton.setChecked(o.getIfOwner() == 1);
            switchButton.setClickable(false);
            itemLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    changeState(o);
                }
            });
        }
    }

    private void changeState(final TotalAssetAddBean.AllTrusteeshipCoinBean bean) {
        HashMap<String, String> params = new HashMap<>();
//        > userId  用户编号(手机号)
//                > trusteeshipCoinId   币编号
//                > type  类型 0是取消关注 1是关注
        LoadingDataUtilBlack.show(this,getResources().getString(R.string.common_text_loading));
        params.put("userId", EnvironmentVariable.getUserName());
        params.put("trusteeshipCoinId", bean.getTrusteeshipId() + "");
        params.put("type", bean.getIfOwner() == 1 ? "0" : "1");
        TCRequestUtil.getCommonRequest(TAG, "trusteeship/updateUserTrusteeshipCoin", params, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                try {
                    JSONObject jsonObject = JSONObject.fromObject(response);
                    if (jsonObject.optString("result","").equals("success")){
                        bean.setIfOwner(bean.getIfOwner() == 1 ? 0 : 1);
                        addAdapter.notifyDataSetChanged();
                    }else{
                        ToastUtil.showToast(AppContext.getInstance(), "设置失败");
                    }

                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();

                ToastUtil.showToast(AppContext.getInstance(), "设置失败");

            }
        });
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        super.onBackPressed();
    }
}
